package com.gaojinqi.sys.core.shiro.realm;

import com.gaojinqi.base.common.util.JsonUtil;
import com.gaojinqi.sys.modular.rbac.model.Permission;
import com.gaojinqi.sys.modular.rbac.model.Role;
import com.gaojinqi.sys.modular.rbac.model.User;
import com.gaojinqi.sys.modular.rbac.service.PermissionService;
import com.gaojinqi.sys.modular.rbac.service.RoleService;
import com.gaojinqi.sys.modular.rbac.service.UserService;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;

/**
 * Shiro 的授权认证
 *
 * @author gaojinqi
 * @version 1.0
 * @since 2020年04月14日
 */
@Slf4j
public class UsernamePasswordRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;

    /**
     * 认证
     */
    @Override
    public AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取用户的输入的账号.
        String username = (String) authenticationToken.getPrincipal();
        //通过username从数据库中查找 User对象，如果找到，没找到.
        //实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
        User user = userService.findByUserName(username);
        if (user == null) {
            return null;
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user, //用户
                user.getPassword(), //密码
                ByteSource.Util.bytes(user.getSalt()),//salt=username+salt
                getName()  //realm name
        );
        if (log.isDebugEnabled()) {
            log.debug("认证配置-->{}.doGetAuthenticationInfo()，authenticationInfo = {}",
                    this.getClass().getName(), JsonUtil.toJSONString(authenticationInfo));
        }
        return authenticationInfo;
    }

    /**
     * 授权
     */
    @Override
    public AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 权限认证迁移到 jwt 中
        /*SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        User user = (User) principalCollection.getPrimaryPrincipal();
        // 设置角色
        List<Role> roleList = roleService.findRolesByUserId(user.getUserId());
        Set<String> roleIdSet = Sets.newHashSet();
        for (Role role : roleList) {
            roleIdSet.add(role.getRoleId());
            authorizationInfo.addRole(role.getRole());
        }
        // 设置权限
        List<Permission> permissionList = permissionService.findPermissionByRoleId(roleIdSet);
        for (Permission permission : permissionList) {
            authorizationInfo.addStringPermission(permission.getPermission());
        }
        if (log.isDebugEnabled()) {
            log.debug("授权配置-->{}.doGetAuthorizationInfo()，authorizationInfo = {}",
                    this.getClass().getName(), JsonUtil.toJSONString(authorizationInfo));
        }
        return authorizationInfo;*/
        return null;
    }

}
